<?php
// +----------------------------------------------------------------------
// | 购物车处理
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2022 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\store;

use app\common\event\Base;
use app\model\ucenter\User as UserModel;
use app\model\store\Good as GoodModel;
use app\model\store\GoodSku as GoodSkuModel;
use app\model\store\Store as StoreModel;
use app\model\pos\Pos as PosModel;
use app\model\pos\PosVip as PosVipModel;
use think\Db;
use think\Exception;

class Cart extends Base
{

    /**
     * 删除数据
     * @param array $param
     * @param UserModel $user
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public static function createOrder($user = null, $from = 1)
    {
        try {
            // 获取当前用户购物车列表
            $ids = $user->carts()->where('is_select', 1)->column('store_id');


            $stores = [];
            if ($ids) {
                foreach (array_unique($ids) as $id) {
                    $store = StoreModel::where('id', $id)->where('status', 1)->find();
                    if ($store) {
                        $goods = $user->carts()->where('is_select', 1)->where('store_id', $id)->select();
                        $newGoods = [];
                        foreach ($goods as $index => $good) {
                            if ($good['good_sku']['stock'] >= $good['number'] && $good['good'] && $good['good']['status'] == 1 && 1 == $good['good']['is_on_sale']) {
                                $newGoods[] = $good;
                            }
                        }
                        if (count($newGoods)) {
                            $stores[] = [
                                'store' => $store,
                                'goods' => $newGoods
                            ];
                        }
                    }
                }
                if (!count($stores)) {
                    throw new Exception('当前选择商品库存不足，请重新选择');
                }
            } else {
                throw new Exception('当前购物车没有选择购买商品');
            }
            // 第1步 检测禁止发布的情况
            $data['code'] = 0;
            $data['data'] = $stores;
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 购物车下单删除已经下单商品
     * @param UserModel $user
     * @return array
     * @author 微尘 <yicmf@qq.com>
     */
    public static function clearOrder($user): array
    {
        try {
            $data['code'] = 0;
            $data['data'] = $user->carts()->where('is_select', 1)->update(['status' => -2]);
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 获取数据
     * @param array $param
     * @param UserModel $user
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public function lists($user = null, $from = 1)
    {
        try {
            // 获取当前用户购物车列表

            $all_select = 1;
            $all_number = 0;
            $all_price = 0;
            $fail_number = 0;
            if ($from == 'new')
            {
                $goods = $user->carts()->with(['good', 'cover'])->where('type',2)->where('status', 1)->select();
            }else{
                $goods = $user->carts()->with(['pos_vip', 'cover'])->where('type',1)->where('status', 1)->select();
            }

            foreach ($goods as $index => $good) {
                if (1 === $good['is_select']) {
                    $all_number += $good['number'];
                    $all_price += ($good['number'] * $good['price']);
                }
                if ($all_select && 0 == $good['is_select']) {
                    $all_select = 0;
                }
            }
            // 第1步 检测禁止发布的情况
            $data['code'] = 0;
            $data['data']['goods'] = $goods;
            $data['data']['all_number'] = $all_number;
            $data['data']['all_price'] = $all_price;
            $data['data']['all_select'] = $all_select;
            $data['data']['fail_number'] = $fail_number;
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 同步数据
     * @param array $param
     * @param UserModel $user
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public function sysnc(array $param,$user = null, $from = 1)
    {
        try {
            // 获取当前用户购物车列表

            $cart = $user->carts()->where('id', $param['id'])->find();
            if ($cart)
            {
                $cart['number'] = $param['number'];
                $cart['is_select'] = $param['is_select'];
                $cart->save();
            }
            $all_select = 1;
            $all_number = 0;
            $all_price = 0;
            $fail_number = 0;

            $goods = $user->carts()->with(['pos_vip', 'cover'])->where('status', 1)->select();

            foreach ($goods as $index => $good) {
                if (1 === $good['is_select']) {
                    $all_number += $good['number'];
                    $all_price += ($good['number'] * $good['price']);
                }
                if ($all_select && 0 == $good['is_select']) {
                    $all_select = 0;
                }
            }
            // 第1步 检测禁止发布的情况
            $data['code'] = 0;
            $data['data']['goods'] = $goods;
            $data['data']['all_number'] = $all_number;
            $data['data']['all_price'] = $all_price;
            $data['data']['all_select'] = $all_select;
            $data['data']['fail_number'] = $fail_number;
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 购物车转入收藏
     * @param array $param
     * @param UserModel $user
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public function collection($param, $user = null, $from = 1)
    {
        try {
            $result = $user->carts()->where('id', 'in', explode(',', $param['id']))->select();
            if (!$result) {
                throw new Exception('未发现需要操作');
            }
            foreach ($result as $item) {
                if (!$user->collections()->where('sku_id', $item['good_sku_id'])->where('status', 1)->find()) {
                    // 新增
                    $insert = [];
                    $insert['sku_id'] = $item['good_sku_id'];
                    $insert['good_id'] = $item['good_id'];
                    $insert['store_id'] = $item['store_id'];
                    $insert['from'] = $from;
                    $user->collections()->save($insert);
                }
                $item['status'] = -2;
                $item->save();
            }
            // 第1步 检测禁止发布的情况
            $data['code'] = 0;
            $data['message'] = '加入收藏成功';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 勾选|取消勾选购物车内商品
     * @param           $param
     * @param UserModel $user
     * @return mixed
     * @author  : 微尘 <yicmf@qq.com>
     */
    public function check($param, $user)
    {
        try {

            if (empty($param['ids'])) {
                $cart = $user->carts()->where('status', 1)->update(['is_select' => 0]);
            } else {

                $cart = $user->carts()->where('status', 1)->where('id', 'in', $param['ids'])->update(['is_select' => 1]);
                $cart = $user->carts()->where('status', 1)->where('id', 'not in', $param['ids'])->update(['is_select' => 0]);
            }

//				// 验证权限
//				if (!$cart) {
//					throw new Exception('商品不存在');
//				}
//				if ($param['is_select'] != $cart['is_select']) {
//					$cart['is_select'] = $param['is_select'];
//					$cart->save();
//				}
            $data['code'] = 0;
//				$data['data']['is_select'] = $cart['is_select'];
            $data['message'] = '';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 物车内商品数量设置
     * @param           $param
     * @param UserModel $user
     * @return mixed
     * @author  : 微尘 <yicmf@qq.com>
     */
    public function number($param, $user)
    {
        try {

            if (!isset($param['number']) || $param['number'] < 1) {
                throw new Exception('下单数量不正确');
            }

            if (isset($param['from']) && 'good' == $param['from']) {
                $sku = GoodSkuModel::where('sn|id', $param['id'])->where('status', 1)->find();
                // 验证权限
                if (!$sku) {
                    throw new Exception('商品不存在');
                }
                // 增加数量
                if ($sku['stock'] < $param['number']) {
                    throw new Exception('商品库存不足');
                }

                $cart['price'] = $sku['price'];
                $cart['number'] = $param['number'];
            } else {
                $cart = $user->carts()->where('id', $param['id'])->where('status', 1)->find();
//					$cart = $user->carts()->where('sku_sn', $param['sku_sn'])->where('status', 1)->find();
                // 验证权限
                if (!$cart) {
                    throw new Exception('商品不存在');
                }
                $sku = GoodSkuModel::where('id', $cart['good_sku_id'])->where('status', 1)->find();
                // 增加数量
                if ($sku['stock'] < $param['number']) {
                    throw new Exception('商品库存不足');
                }
                $cart['number'] = $param['number'];
                $cart->save();
            }

            $data['code'] = 0;
            $data['data'] = $cart;
            $data['message'] = '';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 物车内商品数量设置
     * @param           $param
     * @param UserModel $user
     * @return mixed
     * @author  : 微尘 <yicmf@qq.com>
     */
    public function update($param, $user = null)
    {
        try {
            $cart = $user->carts()->where('sku_sn', $param['old_sku_id'])->find();
            // 验证权限
            if (!$cart) {
                throw new Exception('商品不存在');
            }
            if ($param['old_sku_id'] != $param['sku_id']) {
                // 更新sku

                $sku = GoodSkuModel::where('id|sn', $param['sku_id'])->where('status', 1)->find();
                if (!$sku) {
                    throw new Exception('商品不存在');
                }

            } else {

                $sku = GoodSkuModel::where('id', $cart['good_sku_id'])->where('status', 1)->find();
            }

            // 增加数量
            if ($sku['stock'] < $param['number']) {
                throw new Exception('商品库存不足');
            }
            $cart['title'] = $sku['title'];
            $cart['cover_id'] = $sku['cover_id'];
            $cart['price'] = $sku['price'];
            $cart['type'] = 1;
            $cart['good_id'] = $sku['good_id'];
            $cart['good_sku_id'] = $sku['id'];
            $cart['sku_sn'] = $sku['sn'];
            $cart['store_id'] = $sku['store_id'];
            $cart['number'] = $param['number'];
            $cart->save();
            $data['code'] = 0;
            $data['data'] = $cart;
            $data['message'] = '';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 添加购物车
     * @param           $param
     * @param UserModel $user
     * @return mixed
     * @author  : 微尘 <yicmf@qq.com>
     */
    public function add($param, $user)
    {
        try {
            if (!$user) {
                throw new Exception('请登录后再试');
            }
            if (isset($param['good_id']))
            {
                $sku = GoodModel::where('id', $param['good_id'])->where('status', 1)->find();
                $cart = $user->carts()->where('good_id', $param['good_id'])->find();
            }else{
                $sku = PosVipModel::where('id', $param['pos_vip_id'])->where('status', 1)->find();

                $cart = $user->carts()->where('pos_vip_id', $param['pos_vip_id'])->find();
            }
            if (!$sku) {
                throw new Exception('商品不存在');
            }
            // 检查合法性

//            if ($sku['good']['status'] != 1 || $sku['good']['is_on_sale'] != 1)
//            {
//                throw new Exception('商品已经下架');
//            }
            if ($cart) {
//                if ($sku['stock']<= $cart['number'])
//                {
//                    throw new Exception('当前商品库存不足');
//                }
                // 增加数量
                $cart['number'] += $param['number'];
                $cart['is_select'] = 1;
                $cart->save();
            } else {
                $cart = [];
                if (isset($param['good_id']))
                {
                    $cart['type'] = 2;
                    $cart['good_id'] = $sku['id'];
                }else{
                    $cart['type'] = 1;
                    $cart['pos_vip_id'] = $sku['id'];
                }
                $cart['number'] = $param['number'];
                $cart['is_select'] = 1;
                $cart['description'] = $sku['description'];
                $cart['title'] = $sku['title'];
                $cart['cover_id'] = $sku['cover_id'];
                $cart['price'] = $sku['price'];
                $user->carts()->save($cart);
            }
            $data['code'] = 0;
            $data['data'] = '添加成功';
            $data['message'] = '添加成功';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 清空失效
     * @param           $param
     * @param UserModel $user
     * @return mixed
     * @author  : 微尘 <yicmf@qq.com>
     */
    public function clearf($user)
    {
        try {
            if (!$user) {
                throw new Exception('请登录后再试');
            }
            $goods = $user->carts()->where('status', 1)->select();
            foreach ($goods as $index => $good) {
                if ($good['good_sku']['stock'] >= $good['number'] && $good['good'] && $good['good']['status'] == 1 && 1 == $good['good']['is_on_sale']) {

                } else {
                    $good['status'] = -2;
                    $good->save();
                }
            }
            $data['code'] = 0;
            $data['message'] = '添加成功';
            $data['data'] = '';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

}
